package cn.iocoder.yudao.module.ai.service.picture;

import cn.iocoder.yudao.module.ai.common.IdUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.module.ai.controller.admin.picture.vo.*;
import cn.iocoder.yudao.module.ai.dal.dataobject.picture.PictureDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.ai.dal.mysql.picture.PictureMapper;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.ai.enums.ErrorCodeConstants.*;

/**
 * 图片 Service 实现类
 *
 * @author zhangyujun
 */
@Service
@Validated
public class PictureServiceImpl implements PictureService {

    @Resource
    private PictureMapper pictureMapper;

    @Override
    public String createPicture(PictureReqVO createReqVO) {
        List arrayList = new ArrayList();
        String[] fileIds = createReqVO.getFileId();
        String msg = "";
        if(createReqVO.getFileId().length>0){
            for (String fileId : fileIds) {
                PictureDO pictureDO = new PictureDO();
                pictureDO.setId(IdUtils.generateId());
                pictureDO.setFileId(fileId);
                pictureDO.setPictureSortId(createReqVO.getPictureSortId());
                pictureDO.setPicName(createReqVO.getPicName());
                pictureDO.setPrompt(createReqVO.getPrompt());
                arrayList.add(pictureDO);

            }
            pictureMapper.insertBatch(arrayList);
            msg = "批量新增成功";
        }else {
            msg = "批量新增失败";
        }
        return msg;
    }

    @Override
    public void updatePicture(PictureReqVO updateReqVO) {
        // 校验存在
        validatePictureExists(updateReqVO.getId());
        // 更新
        PictureDO updateObj = BeanUtils.toBean(updateReqVO, PictureDO.class);
        pictureMapper.updateById(updateObj);
    }

    @Override
    public void deletePicture(String id) {
        // 校验存在
        validatePictureExists(id);
        // 删除
        pictureMapper.deleteById(id);
    }

    private void validatePictureExists(String id) {
        if (pictureMapper.selectById(id) == null) {
            throw exception(PICTURE_NOT_EXISTS);
        }
    }

    @Override
    public PictureDO getPicture(String id) {
        return pictureMapper.selectById(id);
    }

    @Override
    public PageResult<PictureDO> getPicturePage(PicturePageReqVO pageReqVO) {
        return pictureMapper.selectPage(pageReqVO);
    }

}